﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kooboo.Domain;
using System.ComponentModel.Composition;
using System.Data;
using Kooboo.IoC;

namespace Kooboo.Commerce.Repositories
{
    [Export(typeof(ITransactionContext))]
    public class DbTransactionContext : ITransactionContext
    {
        public DbTransactionContext()
        {

        }

        IDbTransaction DbTransaction
        {
            get;
            set;
        }

     
        #region ITransactionContext Members

        public bool IsStarted
        {
            get;
            set;
        }

        public void Begin()
        {
            if (this.IsStarted == false)
            {
                this.IsStarted = true;
                var dataContext = ContextContainer.Current.Resolve<DataWriterContext>();

       

                if (dataContext.Connection.State == ConnectionState.Closed)
                {
                    dataContext.Connection.Open();

                }
                dataContext.Transaction = dataContext.Connection.BeginTransaction();

                this.DbTransaction = dataContext.Transaction;
            }
            
        }

        public void Commit()
        {
            this.DbTransaction.Commit();
        }

        public void Rollback()
        {
            this.DbTransaction.Rollback();
        }

        #endregion

    }
}
